package com.yangluyao.jsr303.hibernate.validator.exception;


import com.yangluyao.jsr303.hibernate.validator.common.Rest;
import com.yangluyao.jsr303.hibernate.validator.common.impl.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author YLY
 * @ClassName ApiExceptionHandler
 * @Date 2020/7/30
 * @Version 1.0.2
 */
@Slf4j
@RestControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Rest handle(HttpServletRequest request, Exception e) {
        String contentType = request.getHeader("Content-Type");
        log.error("统一异常处理 ：\n uri: {}  \n content-type: {}  \n exception: {}", request.getRequestURI(), contentType, e.toString());
        if (e instanceof BindException) {
            BindException bindException = (BindException) e;
            List<ObjectError> allErrors = bindException.getAllErrors();
            ObjectError objectError = allErrors.get(0);
            return HttpResult.error(objectError.getDefaultMessage(), 500, "绑定异常");
        }

        if (e instanceof HttpMessageNotReadableException) {
            return HttpResult.error("请求参数非法！", 500, "Http消息不可读异常");
        }

        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();
            ObjectError objectError = allErrors.get(0);
            return HttpResult.error("方法参数无效异常", 500, objectError.getDefaultMessage());
        }

        if (e instanceof NullPointerException) {
            NullPointerException ex = (NullPointerException) e;
            StackTraceElement[] stackTrace = ex.getStackTrace();
            ex.printStackTrace();
            return HttpResult.error("空指针异常", 500, stackTrace[0].toString());
        }
        return HttpResult.error("出错啦，请稍后再试！", 500, "");
    }
}
